package org.headquarter.object;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.headquarter.accessControl.GroupList;
import org.headquarter.persistance.FileSystemNodeRepository;
import org.headquarter.persistance.LoadError;
import org.headquarter.search.TagList;
import org.headquarter.xml.Xmlable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class Node  implements Xmlable{


    UnicId uid;
    GroupList groups = new GroupList();
    TagList tags = new TagList();
    
    List<Node> childs = new ArrayList<Node>();


    public Element toXml(Document doc){
	Element e = doc.createElement("Node");
	e.setAttribute("type", this.getClass().getName());
	e.setAttribute("uid", uid.toString());
	e.setAttribute("tags", tags.getString());
	e.setAttribute("groups", groups.getString());
	Element c = doc.createElement("Childs");
	for(Node node : childs){
	    c.appendChild(node.toXml(doc));
	}
	return e;
    }

    public void loadXml(Element e) throws ClassNotFoundException, InstantiationException, IllegalAccessException, LoadError{
	if(!StringUtils.isEmpty(e.getAttribute("uid"))){
	    uid = new UnicId(e.getAttribute("uid"));
	    
	}
	tags.set( e.getAttribute("tags"));
	groups.set( e.getAttribute("groups"));

	for(Integer i = 0,n = e.getChildNodes().getLength();i<n;i++) {
	    org.w3c.dom.Node current =  (org.w3c.dom.Node)e.getChildNodes().item(i);
	    if(current instanceof Element){
		Node childNode;
		Element childElement  = (Element)current;

		String type = childElement.getAttribute("type");
		if(type!=null&&type.length()>0){
		    ClassLoader cl = FileSystemNodeRepository.class.getClassLoader();
			Class c = cl.loadClass(type);
			childNode = (Node)c.newInstance();
			childNode.loadXml(childElement);
			childs.add(childNode);
		}else{
		    throw new LoadError();
		}
	    }
	}

    }




    public UnicId getUnicId() {
	// TODO Auto-generated method stub
	return uid;
    }



    public void setUnicId(UnicId unicId) {
	this.uid = unicId;

    }





    public String getString() {
	return null;
    }



    public TagList getTags() {
        return tags;
    }

    public void setGroups(GroupList groups) {
        this.groups = groups;
    }

    public GroupList getGroups() {
	return groups;
    }

    public List<Node> getChilds() {
	return childs;
    }









}
